//
//  TMButtons4.swift
//  ArchitectGenerics
//
//  Created by 姚胜龙 on 2017/6/9.
//  Copyright © 2017年 姚胜龙. All rights reserved.
//

import UIKit

//解决命令并发问题 同步代码块，让队列一个一个执行 -- GCD

class TMButtons4 {

    private var reciver:TetrisMeshine?
    var commands = Array<TetrisCommandProtocal>()
    //创建队列，同步队列
    private var queue = DispatchQueue(label: "Command")

    //初始化
    init(reciver:TetrisMeshine) {
        self.reciver = reciver
    }

    //创建执行命令的方法
    func toLeft() {
        self.addCommand(method: TetrisMeshine.toLeft)
        self.reciver?.toLeft()
    }
    func toRight() {
        self.addCommand(method: TetrisMeshine.toRight)
        self.reciver?.toRight()
    }

    func fastDown() {
        self.addCommand(method: TetrisMeshine.fastDown)
        self.reciver?.fastDown()
    }
    func transform() {
        self.addCommand(method: TetrisMeshine.transform)
        self.add(method: TetrisMeshine.pause(name:a:))
        self.reciver?.transform()
    }

    func add(method:@escaping (TetrisMeshine)->(String, Int)->Void) {
        method(self.reciver!)("xiaoyao", 100)
    }

    //动态的指定命令的类型----添加命令
    func addCommand(method:@escaping (TetrisMeshine)->(Void)->Void) {
        //同步代码块
        self.queue.sync {
            self.commands.append(GenericsCommand<TetrisMeshine>.createCommand(reciver: self.reciver!, instruction: { (reciver) in
                method(reciver)()
            }))
        }
    }

    //撤销命令(一个一个撤销)
    func undoCommand() {
        self.queue.sync {
            if self.commands.count > 0 {
                print("撤销了以下操作：")
                self.commands.removeLast().execute()
            }
        }
    }

    //全部撤销
    func undoAllCommand() {
        self.queue.sync {
            for command in self.commands {
                command.execute()
            }
            print("撤销全部操作")
            self.commands.removeAll()
        }
    }
}
